//
//  QSliderButton.m
//  QMCXDriver
//
//  Created by Massimo on 2017/4/13.
//  Copyright © 2017年 Massimo. All rights reserved.
//


#import "QSliderButton.h"
#define ToRad(deg)      ( (M_PI * (deg)) / 180.0 )
#define ToDeg(rad)      ( (180.0 * (rad)) / M_PI )
#define SQR(x)          ( (x) * (x) )

@interface QSliderButton()
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, assign) id target;
@property (nonatomic, assign)SEL action;
@property (nonatomic, assign)CGPoint beginPoint;
@property (nonatomic, assign)CGPoint endPoint;
@end

//IB_DESIGNABLE
@implementation QSliderButton
@synthesize title = _title;
@synthesize titleColor = _titleColor;
@synthesize isHighlight = _isHighlight;
@synthesize normalColor = _normalColor;
@synthesize highlightColor = _highlightColor;
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

- (instancetype)init{
    if (self = [super init]) {
        
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    if (self = [super initWithCoder:aDecoder]) {
        
    }
    return self;
}
#pragma mark - UIControl Override -

/** Tracking is started **/
-(BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super beginTrackingWithTouch:touch withEvent:event];
    //We need to track continuously
    self.isHighlight = YES;
    self.beginPoint = [touch locationInView:self];
    return YES;
}
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super continueTrackingWithTouch:touch withEvent:event];
    
    //Get touch location
    
    CGPoint lastPoint = [touch locationInView:self];
    self.progress = lastPoint.x;
    NSLog(@"x:%f, y:%f",lastPoint.x,lastPoint.y);
    if (!CGRectContainsPoint(self.bounds, lastPoint)) {
        [self resetValue];
        return NO;
    }
    
    [self sendActionsForControlEvents:UIControlEventValueChanged];
    return YES;
}
/** Track is finished **/
-(void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super endTrackingWithTouch:touch withEvent:event];
    
    self.endPoint = [touch locationInView:self];
    CGFloat progress = _endPoint.x - _beginPoint.x;
    [self resetValue];
    
    if (progress < self.bounds.size.width * 0.2) {
        return;
    }
    
    if ([self.target respondsToSelector:self.action]) {
        [self.target performSelector:self.action withObject:self];
    }
}

- (void)resetValue{
    self.isHighlight = NO;
    self.beginPoint = CGPointZero;
    self.endPoint = CGPointZero;
}


#pragma mark - Math -

/** Move the Handle **/
-(void)movehandle:(CGPoint)lastPoint{
    
    //Get the center
//    CGPoint centerPoint = CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
    
    //Calculate the direction from a center point and a arbitrary position.
    //    float currentAngle = AngleFromNorth(centerPoint, lastPoint, NO);
    //    NSLog(@"currentAngle:%f ToRad(self.angle):%f",currentAngle,ToRad(self.angle));
    //    int angleInt = floor(currentAngle);
    //
    //    //Store the new angle
    //    self.angle = 360 - angleInt;
    //      self.angle = angleInt;
    //Update the textfield
    //    int result=self.angle*size/360;
    //    _textField.text =  [NSString stringWithFormat:@"%d", result];
    
    //Redraw
    [self setNeedsDisplay];
}




- (void)drawRect:(CGRect)rect {
    // Drawing code
    //段落格式
    
    CGContextRef context =   UIGraphicsGetCurrentContext();
    
    [self.isHighlight ? self.highlightColor : self.normalColor setFill];
    
    CGContextAddRect(context, rect);
    
    CGContextFillPath(context);
    
    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    textStyle.lineBreakMode = NSLineBreakByWordWrapping;
    textStyle.alignment = NSTextAlignmentCenter;//水平居中
    //字体
    UIFont  *font = [UIFont fontWithName:@"AmericanTypewriter"size:18];
    //构建属性集合
    //在词典中加入文本的颜色 字体 大小
    NSDictionary *attributes = @{NSFontAttributeName:font,
                                 NSParagraphStyleAttributeName:textStyle,
                                 NSForegroundColorAttributeName:self.titleColor};
    
    //获得size
    CGSize strSize = [self.title sizeWithAttributes:attributes];
    CGFloat marginTop = (rect.size.height - strSize.height)/2;
    //垂直居中要自己计算
    CGRect r = CGRectMake(rect.origin.x, rect.origin.y + marginTop,rect.size.width, strSize.height);
    [self.title drawInRect:r withAttributes:attributes];
    
}


#pragma mark - Action target
- (void)addTargetForSlide:(id)target action:(SEL)action{
    self.target = target;
    self.action = action;
}
- (BOOL)isHighlight{
    if (!_isHighlight) {
        _isHighlight = NO;
    }
    return _isHighlight;
}
- (void)setIsHighlight:(BOOL)isHighlight{
    if (_isHighlight != isHighlight) {
        _isHighlight = isHighlight;
        [self setNeedsDisplay];
    }
}

- (void)setTitle:(NSString *)title{
    if (![title isEqualToString:_title]) {
        _title = title;
    }
}

- (NSString *)title{
    if (_title == nil) {
        _title = @"QSliderButton";
    }
    return _title;
}

- (UIColor *)titleColor{
    if (_titleColor == nil) {
        _titleColor = [UIColor blueColor];
    }
    return _titleColor;
}

- (UIColor *)normalColor{
    if (_normalColor == nil) {
        _normalColor = [UIColor whiteColor];
    }
    return _normalColor;
}
- (UIColor *)highlightColor{
    if (_highlightColor == nil) {
        _highlightColor = [UIColor lightGrayColor];
    }
    return _highlightColor;
}



@end
